package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;
@Component
public class BaiDuMapUtils {
    public static final String AK = "cKm3D5uftYGqBUaWtOppla2mhGdL4tdE";
    public static final String SK = "MOVuBkmrvAw61FHK42TJQ3dw4bP6m0LM";
    public static final String URL = "https://api.map.baidu.com/geocoding/v3?";

    public static LinkedHashMap<String, Double> Location(String address) throws Exception {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("address", address);
        params.put("output", "json");
        params.put("ak", AK);

        // 计算 SN
        params.put("sn", caculateSn(address));

        return requestGetSN(URL, params);
    }

    private static LinkedHashMap<String, Double> requestGetSN(String strUrl, Map<String, String> param) throws Exception {
        if (param == null || param.isEmpty()) return null;
        LinkedHashMap<String, Double> map = new LinkedHashMap<>();

        StringBuilder queryString = new StringBuilder(strUrl);
        for (Map.Entry<String, String> pair : param.entrySet()) {
            queryString.append(pair.getKey()).append("=")
                    .append(UriUtils.encode(pair.getValue(), "UTF-8")).append("&");
        }
        queryString.deleteCharAt(queryString.length() - 1);

        URL url = new URL(queryString.toString());
        System.out.println("请求 URL: " + url);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        InputStreamReader isr = new InputStreamReader(connection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();

        String response = buffer.toString();
        System.out.println("API 响应: " + response);

        JSONObject jsonResponse = JSON.parseObject(response);
        if (jsonResponse.getIntValue("status") != 0) {
            System.out.println("百度 API 错误: " + jsonResponse.getString("message"));
            return map;
        }

        JSONObject location = jsonResponse.getJSONObject("result").getJSONObject("location");
        double lng = location.getDoubleValue("lng");
        double lat = location.getDoubleValue("lat");

        map.put("lng", lng);
        map.put("lat", lat);
        return map;
    }

    private static String caculateSn(String address) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        Map<String, String> paramsMap = new LinkedHashMap<>();
        paramsMap.put("address", address);
        paramsMap.put("output", "json");
        paramsMap.put("ak", AK);

        String paramsStr = toQueryString(paramsMap);
        String wholeStr = "/geocoding/v3?" + paramsStr + SK;
        System.out.println("SN 计算原始字符串: " + wholeStr);

        String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
        return MD5(tempStr);
    }

    private static String toQueryString(Map<?, ?> data) throws UnsupportedEncodingException {
        StringBuilder queryString = new StringBuilder();
        for (Map.Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey()).append("=")
                    .append(UriUtils.encode((String) pair.getValue(), "UTF-8")).append("&");
        }
        queryString.deleteCharAt(queryString.length() - 1);
        return queryString.toString();
    }

    private static String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : array) {
                sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }
}

